<!--
 * @Description: 账号密码登录
 * @Author: zhailei
 * @Date: 2021-06-02 13:38:09
 * @LastEditTime: 2021-12-01 13:37:57
 * 
 * @FilePath: \com__wwwe:\wwwroot\Vue\-cloud-vue\src\pages\user\Login.vue
-->
<template>
  <div class="login-mian-content">
    <div class="loginHeader" v-if="!isMobile">
      <img class="loginLogo" :src="loginLogo" />
      <div class="loginName">{{ loginName }}</div>
    </div>
    <a-form
      id="formLogin"
      class="user-layout-login"
      ref="formLogin"
      :form="form"
      @submit="handleSubmit"
    >
      <a-alert
        v-if="isLoginError"
        type="error"
        showIcon
        style="margin-bottom: 24px"
        :message="errMessage"
      />
      <a-form-item>
        <a-input
          size="large"
          type="text"
          placeholder="请输入账号"
          allowClear
          v-decorator="[
            'userNameId',
            {
              rules: [{ required: true, message: '请输入帐号' }],
              validateTrigger: 'blur',
              initialValue: '',
            },
          ]"
        >
          <a-icon
            slot="prefix"
            type="user"
            :style="{ color: 'rgba(0,0,0,.25)' }"
          />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input-password
          size="large"
          autocomplete="false"
          placeholder="请输入密码"
          v-decorator="[
            'password',
            {
              rules: [{ required: true, message: '请输入密码' }],
              validateTrigger: 'blur',
              initialValue: '',
            },
          ]"
          allowClear
        >
          <a-icon
            slot="prefix"
            type="lock"
            :style="{ color: 'rgba(0,0,0,.25)' }"
          />
        </a-input-password>
      </a-form-item>
      <a-row :gutter="8">
        <a-col class="gutter-row" :span="15">
          <a-form-item>
            <a-input
              size="large"
              type="text"
              placeholder="请输入验证码"
              :maxLength="4"
              v-decorator="[
                'code',
                {
                  rules: [{ required: true, message: '请输入验证码' }],
                  validateTrigger: 'blur',
                },
              ]"
            >
              <icon-fonts
                slot="prefix"
                icon="icon-yanzhengma"
                :style="{ color: 'rgba(0,0,0,.25)' }"
                type="small"
              ></icon-fonts>
            </a-input>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row text-right" :span="8" @click="getCode">
          <img
            v-if="requestCodeSuccess"
            :contentWidth="90"
            style="border: 1px solid #e2e2e2;border-radius: 5px;"
            :src="identifyCode"
            title="看不清?点击切换"
          />

          <img v-else src="~@/assets/img/code.png" alt="" class="code-img" />
        </a-col>
      </a-row>

      <a-form-item class="margin-top-sm">
        <a-button
          size="large"
          type="primary"
          block
          htmlType="submit"
          class="login-button"
          :loading="loginBtn"
          :disabled="loginBtn"
          >登录
        </a-button>
      </a-form-item>
    </a-form>
    <div
      class="user-login-register margin-top-sm"
      v-if="customActiveKey === '1'"
    >
      <!-- <p class="register" v-show="isSaaSEnabled" style="float:left">
            没有账号?
            <router-link :to="{ name: 'register' }"> 注册</router-link>
          </p> -->
      <p class="forget" style="float: right">
        <router-link :to="routerLinkParam"> 忘记密码?</router-link>
      </p>
    </div>
  </div>
</template>

<script>
import { JSEncrypt } from "jsencrypt";
import { mapGetters, mapActions } from "vuex";
import store from "@/store";
import { getQueryString } from "@/services/common";
import { mapState } from "vuex";
import { getSystemConfig } from "@/utils/TopVUI.js";

export default {
  data() {
    return {
      //ewsd0001
      requestCodeSuccess: false,
      identifyCode: "",
      form: this.$form.createForm(this),
      loginBtn: false,
      isLoginError: false,
      errMessage: "",
      isSaaSEnabled: false,
      state: {
        time: 60,
        smsSendBtn: false,
      },
      customActiveKey: "1",
    };
  },
  created() {
    this.getCode();
    this.getSaaSEnabled();
  },
  mounted() {
    this.form.setFieldsValue({
      userNameId: "",
      password: "",
    });
  },
  computed: {
    ...mapState("setting", ["domain", "isMobile"]),
    routerLinkParam() {
      if (this.$route.query.from) {
        return {
          name: "ForgetPwd",
          query: {
            from: this.$route.query.from,
          },
        };
      } else {
        return {
          name: "ForgetPwd",
        };
      }
    },
    loginLogo() {
      return getSystemConfig(
        "loginLogo",
        "https://zysd-shanghai.oss-cn-shanghai.aliyuncs.com/emis/logo.png"
      );
    },
    loginName() {
      return getSystemConfig("loginName", "低代码开发平台");
    },
  },
  methods: {
    ...mapActions(["Login"]),
    // 获取验证码
    getCode() {
      let that = this;
      that
        .$post("/system/getVerificationImg.api")
        .then((res) => {
          if (200 == res.statusCode) {
            that.form.setFieldsValue({ code: "" });
            that.identifyCode = res.message;
            that.requestCodeSuccess = true;
          } else {
            that.requestCodeSuccess = false;
          }
        })
        .catch(() => {
          this.requestCodeSuccess = false;
        });
    },
    // 是否开始多租户
    getSaaSEnabled() {
      this.$post("/system/config/isSaaSEnabled.api").then((res) => {
        if (res.statusCode === 300) {
          return true;
        }
        this.isSaaSEnabled = res;
      });
    },
    handleSubmit(e) {
      e.preventDefault();
      const {
        form: { validateFields },
        customActiveKey,
        Login,
      } = this;

      this.loginBtn = true;
      const validateFieldsKey = ["userNameId", "password", "code"];

      validateFields(
        validateFieldsKey,
        {
          force: true,
        },
        (err, values) => {
          if (!err) {
            const loginParams = { ...values };
            let publicKey =
              "-----BEGIN PUBLIC KEY-----\n" +
              "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5bxAa8KASxYwrRe7kP8XjF8LO\n" +
              "pbAqDVj3HZEu+j/8zp75TRYXnOeNFV4QjPktsvTI0ErtH2Bzvkedkhm5JQYxQ/yv\n" +
              "nGMtbvV3VNkaKtT+fVYtBN5bF1IXJP5YLR/IvevMx5h3WqTiwZG4Df/QJ0Abenl6\n" +
              "GUfXZi0aR85+ysc6UwIDAQAB\n" +
              "-----END PUBLIC KEY-----";
            let encryptor = new JSEncrypt(); // 新建JSEncrypt对象
            let loginPasswd = this.$md5(loginParams.password); // 对密码进行加密
            //在本地存储
            localStorage.setItem("loginPasswd", loginPasswd);
            encryptor.setPublicKey(publicKey); // 设置公钥
            let rsaPassWord = encryptor.encrypt(loginParams.password); // 对密码进行加密
            loginParams.password = rsaPassWord;

            Login(loginParams)
              .then((res) => this.loginSuccess(res))
              .catch((err) => this.requestFailed(err));
          }
        }
      );
    },
    loginSuccess(res) {
      //   this.getLanguageMap();
      this.$router
        .push({
          path: "/system/portal/index",
          query: {
            type: "login",
          },
        })
        .catch(() => {
          console.log("登录跳转首页出错,这个错误从哪里来的");
        });
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.loginBtn = false;
      }, 1000);
      this.isLoginError = false;
    },
    requestFailed(err) {
      this.getCode();
      this.isLoginError = true;
      this.errMessage = err.message;
      this.loginBtn = false;
      setTimeout(() => {
        this.isLoginError = false;
      }, 3000);
    },
    navTo(val) {
      this.$router.push({ name: val });
    },
    changeTabs(key) {
      this.customActiveKey = key;
    },
    // 获取多语言数据
    getLanguageMap() {
      this.$post("/system/sysLanguage/getLanguageMap").then((langRes) => {
        if (langRes.statusCode === 200) {
          let langData = langRes.data;
          this.$post("/system/sysLanguageConfig/selectAll").then((typeRes) => {
            let langTypeData = [];
            if (typeRes.statusCode === 200) {
              langTypeData = typeRes.data.map((e) => e.configValue);
            }
            let langTypeMap = {};
            for (let i = 0; i < langTypeData.length; i++) {
              let langDataMap = {};
              for (let key in langData) {
                if (key.indexOf("_" + langTypeData[i]) >= 0) {
                  langDataMap[key.replace("_" + langTypeData[i], "")] =
                    langData[key];
                  langTypeMap[langTypeData[i]] = langDataMap;
                }
              }
              this.$i18n.setLocaleMessage(
                langTypeData[i],
                langTypeMap[langTypeData[i]]
              );
            }
          });
        }
      });
    },
  },
};
</script>
<style lang="less">
.login-right {
  .ant-tabs-bar {
    margin-bottom: 30px !important;
  }
}

.login_content {
  &.mobile {
    .login-right {
      .ant-tabs-bar {
        margin-bottom: 20px !important;
      }

      button.login-button {
        margin-top: 10px;
      }

      .user-login-register {
        margin-top: 10px !important;
      }
    }
  }
}
.loginHeader {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  .loginLogo {
    width: 32px;
    margin-right: 10px;
  }
  .loginName {
    font-size: 18px;
    font-weight: bold;
  }
}
</style>
